<template>
    <div>
        <el-card>
            <!-- 查询表单 -->
            <el-form :inline="true">
                <el-form-item label="版本号">
                    <el-input v-model="query.version" @keyup.enter.native="fetchList" clearable
                        placeholder="支持1.2.3格式" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="fetchList">查询</el-button>
                    <el-button @click="resetQuery">重置</el-button>
                </el-form-item>
            </el-form>

            <div style="margin-bottom:8px;text-align:right">
                <el-button type="primary" @click="openDialog()">新增配置</el-button>
            </div>

            <el-table :data="list" :loading="loading" border>
                <el-table-column prop="pk" align="center" label="环境" width="120">
                    <template slot-scope="scope">
                        <el-tag :type="scope.row.pk === prodPk ? 'success' : 'danger'">
                            {{ envLabel(scope.row.pk) }}
                        </el-tag>
                    </template>
                </el-table-column>

                <el-table-column prop="min_version" align="center" width="160" label="最低版本" />
                <el-table-column prop="max_version" align="center" width="160" label="最高版本" />
                <el-table-column label="功能列表" align="center">
                    <template slot-scope="scope">
                        <span v-for="f in parseFeature(scope.row.feature_list)" :key="f.featureName">
                            <el-tag style="margin:2px">{{ featureNameLabel(f.featureName) }}</el-tag>
                        </span>
                    </template>
                </el-table-column>
                <el-table-column prop="updated_at" align="center" label="修改时间" width="200" />
                <el-table-column label="操作" width="280" align="center">
                    <template slot-scope="scope">
                        <el-button type="primary" size="mini" @click="openDialog(scope.row)">编辑</el-button>
                        <el-button size="mini" v-if="scope.row.pk === prodPk" type="danger"
                            @click="switchEnv(scope.row, devPk)">
                            切换开发
                        </el-button>
                        <el-button size="mini" v-if="scope.row.pk === devPk" type="success"
                            @click="switchEnv(scope.row, prodPk)">
                            切换生产
                        </el-button>
                        <el-button type="danger" size="mini" @click="deleteRow(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <el-pagination v-if="total > 0" :current-page.sync="query.page" :page-size.sync="query.pageSize"
                :total="total" @current-change="fetchList" @size-change="fetchList"
                style="margin:12px 0; text-align:center" />
        </el-card>

        <!-- 新增&编辑弹窗 -->
        <el-dialog :visible.sync="dialogVisible" :title="form.id ? '编辑配置' : '新增配置'" width="920px"
            :before-close="handleClose">
            <template slot="title">
                <span>
                    {{ form.id ? '编辑配置' : '新增配置' }}
                    <el-button v-if="!form.id" type="primary" size="mini" class="import-btn" :loading="importLoading"
                        @click="importLatestConfig">导入上个版本配置</el-button>
                </span>
            </template>
            <el-form :model="form" ref="form" :rules="rules" label-width="100px" label-position="left">

                <!-- 版本号配置 -->
                <div class="form-section">
                    <div class="section-title">版本配置</div>
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="最低版本" prop="min_version">
                                <el-input v-model="form.min_version" placeholder="如：1.0.0" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="最高版本" prop="max_version">
                                <el-input v-model="form.max_version" placeholder="如：2.5.3" clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </div>

                <!-- 功能配置 -->
                <div class="form-section">
                    <div class="section-title">
                        功能配置
                        <span class="section-subtitle">（至少配置一个功能）</span>
                    </div>

                    <div class="feature-list">
                        <div v-for="(feature, featureIdx) in form.feature_list" :key="featureIdx" class="feature-card">

                            <!-- 功能头部 -->
                            <div class="feature-header">
                                <span class="feature-index">功能 {{ featureIdx + 1 }}</span>
                                <div style="display: flex;">
                                    <el-button v-if="form.feature_list.length > 1" size="mini" type="text"
                                        icon="el-icon-delete" class="delete-btn" @click="removeFeature(featureIdx)">
                                        删除功能
                                    </el-button>
                                    <el-button style="margin-left: 20px;" size="mini" type="text" icon="el-icon-s-tools"
                                        class="tools-btn" @click="debug(featureIdx)">
                                        调试
                                    </el-button>
                                </div>
                            </div>

                            <!-- 功能名选择 -->
                            <el-form-item label="功能名称" :prop="`feature_list.${featureIdx}.featureName`"
                                :rules="[{ required: true, message: '请选择功能名称', trigger: 'change' }]">
                                <el-select v-model="feature.featureName" placeholder="请选择功能" filterable clearable
                                    style="width: 100%">
                                    <el-option v-for="item in featureNameOptions" :key="item.value" :label="item.label"
                                        :value="item.value" :disabled="featureNameIsSelected(item.value, featureIdx)" />
                                </el-select>
                            </el-form-item>

                            <!-- 模型组列表 -->
                            <div class="model-groups">
                                <div class="model-group-title">模型配置</div>

                                <div v-for="(mg, mgIdx) in feature.modelGroups" :key="mgIdx" class="model-group-card">

                                    <!-- 模型组头部 -->
                                    <div class="model-group-header">
                                        <span class="model-group-index">配置组 {{ mgIdx + 1 }}</span>
                                        <el-button v-if="feature.modelGroups.length > 1" size="mini" type="text"
                                            icon="el-icon-delete" class="delete-btn"
                                            @click="removeGroup(featureIdx, mgIdx)">
                                            删除组
                                        </el-button>
                                    </div>

                                    <!-- 模型选择 -->
                                    <el-form-item label="选择模型"
                                        :prop="`feature_list.${featureIdx}.modelGroups.${mgIdx}.models`"
                                        :rules="[{ required: true, message: '请至少选择一个模型', trigger: 'change' }]">
                                        <el-select v-model="mg.models" multiple filterable clearable style="width: 100%"
                                            placeholder="请选择模型">
                                            <el-option v-for="opt in modelOptions" :key="opt.value" :label="opt.label"
                                                :value="opt.value" />
                                        </el-select>
                                    </el-form-item>

                                    <!-- 提示词 -->
                                    <el-form-item label="提示词"
                                        :prop="`feature_list.${featureIdx}.modelGroups.${mgIdx}.prompt`"
                                        :rules="[{ required: true, message: '请输入提示词', trigger: 'blur' }]">
                                        <el-input v-model="mg.prompt" type="textarea" :rows="4"
                                            placeholder="请输入提示词内容..." show-word-limit :maxlength="1000"
                                            style="width: 100%" />
                                    </el-form-item>
                                    <el-form-item label="补充提示词"
                                        :prop="`feature_list.${featureIdx}.modelGroups.${mgIdx}.extraPrompt`">
                                        <el-input v-model="mg.extraPrompt" type="textarea" :rows="4"
                                            placeholder="请输入补充提示词内容..." show-word-limit :maxlength="1000"
                                            style="width: 100%" />
                                    </el-form-item>
                                </div>

                                <!-- 新增模型组按钮 -->
                                <div class="add-group-btn">
                                    <el-button size="small" type="primary" plain icon="el-icon-plus"
                                        @click="addGroup(featureIdx)">
                                        新增模型组
                                    </el-button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 新增功能按钮 -->
                    <div class="add-feature-btn">
                        <el-button type="primary" plain icon="el-icon-plus" @click="addFeature">
                            新增功能
                        </el-button>
                    </div>
                </div>
            </el-form>

            <!-- 底部按钮 -->
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" :loading="saveLoading" @click="handleSave">
                    {{ saveLoading ? '保存中...' : '确定保存' }}
                </el-button>
            </div>
        </el-dialog>
        <el-dialog :visible.sync="dialogVisible1" title="调试" width="1000px" :before-close="handleClose1">
            <div>
                <!-- 动态参数输入 -->
                <el-input type="textarea" v-model="debugParamsContent" :placeholder="'请输入'" clearable />
                <div style="margin:12px 0;text-align:right">
                    <el-button type="primary" @click="handleDebug" :loading="debugLoading">调试</el-button>
                    <el-button type="success" @click="saveAffirmationsToDB" v-if="canInsertAffirmations"
                        :loading="insertLoading" style="margin-left:10px">
                        入库
                    </el-button>
                </div>
                <el-divider />
                <div>
                    <v-md-preview :text="messageRes.content"></v-md-preview>
                </div>
            </div>
        </el-dialog>

    </div>
</template>


<script>
import axios from 'axios'
export default {
    data() {
        return {
            featureNameIdx:'',
            dialogVisible1: false,
            debugLoading: false,
            debugParamsContent: '',
            messageRes: {
                content: "",
            }, // 后端返回内容
            debugParams: {}, // 用于数据绑定
            debugParamsList: [  // 动态参数定义
                { key: 'param1', label: '参数1' },
                { key: 'param2', label: '参数2' },
                { key: 'param3', label: '参数3' },
                { key: 'param4', label: '参数4' }
            ],
            query: { version: '', page: 1, pageSize: 10 },
            list: [

            ],
            total: 0,
            loading: false,
            dialogVisible: false,
            saveLoading: false,
            form: {},
            featureIdx: null,
            prodPk: "com.finger.withYou",
            devPk: "com.withYou.TestApp",
        
            featureNameOptions: [
                { value: 'tarot_interpretation_theme', label: '宇宙来信-主题' },
                { value: 'tarot_interpretation_moon_phase', label: '宇宙来信-月相' },
                { value: 'moon_phase_guidance', label: '月相指引' },
                { value: 'affirmation_generation', label: '肯定语生成' },
                { value: 'affirmation_energy_recognition', label: '肯定语能量识别' },
                { value: 'affirmation_universe_reply', label: '肯定语获取宇宙回应' },
                { value: 'affirmation_high_freq_recommend', label: '肯定语推荐' },
                { value: 'tarot_spread_a', label: '塔罗牌阵A' },
            ],
            modelOptions: [
                { value: "Qwen/Qwen2.5-32B-Instruct", label: "Qwen/Qwen2.5-32B-Instruct" },
                { value: "Qwen/Qwen2.5-14B-Instruct", label: "Qwen/Qwen2.5-14B-Instruct" },
                { value: "Qwen/Qwen2.5-7B-Instruct", label: "Qwen/Qwen2.5-7B-Instruct" },
                { value: "internlm/internlm2_5-7b-chat", label: "internlm/internlm2_5-7b-chat" },
                { value: "Qwen/Qwen2-7B-Instruct", label: "Qwen/Qwen2-7B-Instruct" },
                { value: "Pro/THUDM/gIm-4-9b-chat", label: "Pro/THUDM/gIm-4-9b-chat" },
                { value: "THUDM/glm-4-9b-chat", label: "THUDM/glm-4-9b-chat" },
                { value: "THUDM/GLM-4-32B-0414", label: "THUDM/GLM-4-32B-0414" },
                { value: "Pro/Qwen/Qwen2.5-VL-7B-Instruct", label: "Pro/Qwen/Qwen2.5-VL-7B-Instruct" },
                { value: "deepseek-ai/deepseek-vl2", label: "deepseek-ai/deepseek-vl2" },
                { value: "Qwen/Qwen2.5-VL-32B-Instruct", label: "Qwen/Qwen2.5-VL-32B-Instruct" },
                { value: "Qwen/Qwen3-Next-80B-A3B-Instruct", label: "Qwen/Qwen3-Next-80B-A3B-Instruct" },
            ],
            rules: {
                min_version: [
                    { required: true, message: '必填', trigger: 'blur' },
                    { pattern: /^\d+\.\d+\.\d+$/, message: '格式为1.0.0', trigger: 'blur' }
                ],
                max_version: [
                    { required: true, message: '必填', trigger: 'blur' },
                    { pattern: /^\d+\.\d+\.\d+$/, message: '格式为1.0.0', trigger: 'blur' }
                ]
            },
            insertLoading: false,
            insertAffirmationList: null // 临时存解析结果
        }
    },
    computed: {
        // 只要messageRes.content可被解析为你的JSON格式才出现按钮
        canInsertAffirmations() {
            if (this.featureNameIdx != 'affirmation_generation') return false;
            if (!this.messageRes || !this.messageRes.content) return false;
            let text = this.messageRes.content.trim();

            // 1. 去除 markdown ```json``` 和 ```
            text = text.replace(/``` ?json/gi, '').replace(/```/g, '').trim();

            // 2. 去除每行 // 注释
            text = text.split('\n').map(line => {
                const idx = line.indexOf('//');
                return idx > -1 ? line.slice(0, idx) : line;
            }).join('\n');

            // 3. 去结尾多余逗号（对象/数组内）
            text = text.replace(/,\s*([\}\]])/g, '$1');

            // 4. 去掉所有空白行
            text = text.split('\n').map(line => line.trim()).filter(line => !!line).join('\n');

            // 5. 尝试整体 parse
            try {
                const obj = JSON.parse(text);
                if (
                    obj && typeof obj === 'object' &&
                    obj.affirmations &&
                    Array.isArray(obj.affirmations.content) &&
                    obj.affirmations.metadata
                ) return true;
            } catch (e) { /* fallback */ }

            // 6. 尝试匹配单个大括号片段
            let match = text.match(/\{[\s\S]*\}/);
            if (match && match[0]) {
                try {
                    let fixStr = match[0].replace(/,\s*([\}\]])/g, '$1');
                    const obj = JSON.parse(fixStr);
                    if (
                        obj && typeof obj === 'object' &&
                        obj.affirmations &&
                        Array.isArray(obj.affirmations.content) &&
                        obj.affirmations.metadata
                    ) return true;
                } catch (e) { }
            }

            // 7. 再宽容一层，匹配多个大括号片段
            let matches = text.match(/\{[^]*?\}/g);
            if (matches && matches.length) {
                for (let mm of matches) {
                    try {
                        let fixStr = mm.replace(/,\s*([\}\]])/g, '$1');
                        const obj = JSON.parse(fixStr);
                        if (
                            obj && typeof obj === 'object' &&
                            obj.affirmations &&
                            Array.isArray(obj.affirmations.content) &&
                            obj.affirmations.metadata
                        ) return true;
                    } catch (e) { }
                }
            }
            // 8. 都不行就false
            return false;
        }

    },
    methods: {
        async saveAffirmationsToDB() {
            let content = this.messageRes.content.trim();

            // 强力清洗
            // 1. 去除 markdown 标记
            content = content.replace(/``` ?json/gi, '')
                .replace(/```/g, '')
                .trim();

            // 2. 去除行尾 //
            content = content.split('\n').map(line => {
                const idx = line.indexOf('//');
                return idx > -1 ? line.slice(0, idx) : line;
            }).join('\n');

            // 3. 去结尾逗号
            content = content.replace(/,\s*([\}\]])/g, '$1');

            // 4. 去空行
            content = content.split('\n').map(line => line.trim()).filter(line => !!line).join('\n');

            // 5. 解析，支持整体和片段
            let obj = null;
            let parseOk = false;
            // 整体
            try {
                obj = JSON.parse(content);
                parseOk = true;
            } catch (e) { }
            // 单个片段
            if (!parseOk) {
                let match = content.match(/\{[\s\S]*\}/);
                if (match && match[0]) {
                    try {
                        let fixStr = match[0].replace(/,\s*([\}\]])/g, '$1');
                        obj = JSON.parse(fixStr);
                        parseOk = true;
                    } catch (e2) { }
                }
            }
            // 多片段（以免AI多个大括号都贴出来）
            if (!parseOk) {
                let matches = content.match(/\{[^]*?\}/g);
                if (matches && matches.length) {
                    for (let mm of matches) {
                        try {
                            let fixStr = mm.replace(/,\s*([\}\]])/g, '$1');
                            obj = JSON.parse(fixStr);
                            parseOk = true;
                            break;
                        } catch (e3) { }
                    }
                }
            }

            if (!parseOk || !obj || !obj.affirmations || !obj.affirmations.content || !obj.affirmations.metadata) {
                return this.$message.error("回复内容解析失败～");
            }

            const meta = obj.affirmations.metadata;
            const list = (obj.affirmations.content || []).map(text => ({
                theme: meta.theme,
                language: meta.language,
                moon_phase: '', // 先空
                sentence: text
            }));
            this.insertLoading = true;
            console.log(list)
            try {
                const { data } = await axios.post('https://xiaoshuchengzhang.com/node/Tarot/affirmation/insertBatch', { list });
                if (data && data.code === 0) {
                    this.$message.success('入库成功！');
                } else {
                    this.$message.error(data.msg || '入库失败');
                }
            } catch (e) {
                this.$message.error('接口异常：' + (e.msg || e.message));
            }
            this.insertLoading = false;
        },
        // 切换环境
        async switchEnv(row, targetPk) {
            this.$confirm(
                `确定将此配置切换到${this.envLabel(targetPk)}环境吗？`,
                "环境切换",
                { type: "warning" }
            ).then(async () => {
                // 你需要后端提供一个切换pk的接口，比如 /modelConfig/switchEnv
                const { data } = await axios.post('https://xiaoshuchengzhang.com/node/Tarot/modelConfig/switchEnv', {
                    id: row.id,
                    pk: targetPk
                });
                if (data.code === 0) {
                    this.$message.success('环境切换成功');
                    this.fetchList();
                } else {
                    this.$message.error(data.msg || '环境切换失败');
                }
            });
        },
        envLabel(pk) {
            if (pk === this.prodPk) return '生产';
            if (pk === this.devPk) return '开发';
            return pk || '未知';
        },
        handleClose(done) {
            this.dialogVisible = false;
            this.$nextTick(() => {
                if (this.$refs.form) this.$refs.form.clearValidate();
            });
            if (done) done();
        },
        featureNameLabel(val) {
            const it = this.featureNameOptions.find(i => i.value === val)
            return it ? it.label : val
        },
        // 如果你允许多个feature，以下辅助防止重复（也可省略！）
        featureNameIsSelected(val, idx) {
            const arr = this.form.feature_list.map(f => f.featureName);
            // 已选过且不是自己
            return arr.includes(val) && this.form.feature_list[idx]?.featureName !== val;
        },
        // 若只允许一个feature关联一种功能，这个返回false即可
        selectDisabled(idx) { return false },
        parseFeature(f) {
            if (!f) return []
            if (typeof f === 'string') try { return JSON.parse(f) } catch { return [] }
            return Array.isArray(f) ? f : []
        },
        async fetchList() {
            this.loading = true
            try {
                const { data } = await axios.post('https://xiaoshuchengzhang.com/node/Tarot/modelConfig/list', {
                    page: this.query.page,
                    pageSize: this.query.pageSize,
                    version: this.query.version
                })
                if (data.code === 0) {
                    // 解析feature_list
                    this.list = data.data.list.map(row => ({
                        ...row,
                        feature_list: this.parseFeature(row.feature_list)
                    }))
                    this.total = data.data.total
                } else this.$message.error(data.msg || '获取失败')
            } finally { this.loading = false }
        },
        resetQuery() {
            this.query.version = ''; this.query.page = 1; this.fetchList()
        },
        // 打开弹窗新增/编辑
        openDialog(row) {
            if (row) {
                // 编辑
                const feature_list = this.parseFeature(row.feature_list).map(f => ({
                    ...f,
                    modelGroups: (f.modelGroups || []).map(g => ({
                        ...g,
                        models: Array.isArray(g.models)
                            ? g.models
                            : (typeof g.models === 'string'
                                ? g.models.split(',').map(s => s.trim()).filter(Boolean)
                                : [])
                    }))
                }))
                this.form = {
                    id: row.id,
                    min_version: row.min_version,
                    max_version: row.max_version,
                    feature_list: feature_list.length ? feature_list : [this.defaultFeature()]
                }
            } else {
                // 新建
                this.form = {
                    min_version: '',
                    max_version: '',
                    feature_list: [this.defaultFeature()]
                }
            }
            this.dialogVisible = true
            this.$nextTick(() => {
                // form可能还没渲染，需要nextTick后操作
                this.$refs.form && this.$refs.form.clearValidate && this.$refs.form.clearValidate();
            })
        },


        defaultFeature() {
            return {
                featureName: '',
                modelGroups: [{ prompt: '', models: [] }]
            }
        },

        // 动态表单操作
        addFeature() {
            this.form.feature_list.push(this.defaultFeature())
        },
        removeFeature(idx) {
            if (this.form.feature_list.length <= 1) return
            this.form.feature_list.splice(idx, 1)
        },
        addGroup(fidx) {
            this.form.feature_list[fidx].modelGroups.push({ prompt: '', models: [] })
        },
        removeGroup(fidx, gidx) {
            if (this.form.feature_list[fidx].modelGroups.length <= 1) return
            this.form.feature_list[fidx].modelGroups.splice(gidx, 1)
        },
        // 保存
        async handleSave() {
            await this.$refs.form.validate()
            // modelGroups 里直接传 models 数组，别 split 什么字符串
            let feat = (this.form.feature_list || []).map(f => ({
                ...f,
                modelGroups: (f.modelGroups || []).map(g => ({
                    prompt: g.prompt,
                    extraPrompt: g.extraPrompt,
                    models: Array.isArray(g.models) ? g.models : []
                }))
            }))
            if (!feat.length) return this.$message.warning('至少包含一个功能')
            this.saveLoading = true
            try {
                const params = {
                    ...this.form,
                    feature_list: JSON.stringify(feat),
                    status: 1
                }
                const { data } = await axios.post('https://xiaoshuchengzhang.com/node/Tarot/modelConfig/save', params)
                if (data.code === 0) {
                    this.$message.success('保存成功')
                    this.dialogVisible = false
                    this.fetchList()
                } else {
                    this.$message.error(data.msg || '保存失败')
                }
            } finally { this.saveLoading = false }
        },

        // 删除
        deleteRow(row) {
            this.$confirm('确定要删除此配置吗？', '提示', { type: 'warning' }).then(async () => {
                try {
                    const { data } = await axios.post('https://xiaoshuchengzhang.com/node/Tarot/modelConfig/delete', { id: row.id })
                    if (data.code === 0) {
                        this.$message.success('已删除')
                        this.fetchList()
                    } else this.$message.error(data.msg || '删除失败')
                } catch (err) { this.$message.error(err.msg || '删除失败') }
            })
        },
        async importLatestConfig() {
            this.importLoading = true;
            try {
                // 假设你list接口按id或者created_at倒序，查第一页1条就是最新的
                const { data } = await axios.post('https://xiaoshuchengzhang.com/node/Tarot/modelConfig/list', {
                    page: 1,
                    pageSize: 1
                });
                if (data.code === 0 && data.data.list && data.data.list.length > 0) {
                    const latest = data.data.list[0];
                    // 拷贝并处理下，防止undefined
                    const feature_list = this.parseFeature(latest.feature_list).map(f => ({
                        ...f,
                        modelGroups: (f.modelGroups || []).map(g => ({
                            ...g,
                            models: Array.isArray(g.models)
                                ? g.models
                                : (typeof g.models === 'string'
                                    ? g.models.split(',').map(s => s.trim()).filter(Boolean)
                                    : [])
                        }))
                    }));
                    // 赋值到form，注意不赋id！
                    this.form = {
                        min_version: latest.min_version || '',
                        max_version: latest.max_version || '',
                        feature_list: feature_list.length ? feature_list : [this.defaultFeature()]
                    }
                    // 清除历史校验红框
                    this.$nextTick(() => {
                        if (this.$refs.form) this.$refs.form.clearValidate();
                    });
                    this.$message.success('已导入上个版本配置，请根据需要修改后保存！');
                } else {
                    this.$message.warning('没有可导入的上个版本配置！');
                }
            } catch (err) {
                this.$message.error('导入失败: ' + (err.msg || err.message));
            }
            this.importLoading = false;
        },
        // 打开调试弹窗并初始化参数
        debug(featureIdx) {
            this.featureIdx = featureIdx
            this.featureNameIdx = this.form.feature_list[this.featureIdx].featureName
            this.debugParamsContent = '';

            this.messageRes.content = '';
            this.dialogVisible1 = true;
        },

        // 关闭调试弹窗逻辑
        handleClose1(done) {
            this.dialogVisible1 = false;
            this.messageRes = {};
            this.debugParamsContent = '';
            if (done) done();
        },
        handleResult(result) {

            this.$set(this.messageRes, "content", this.messageRes.content + result);
        },
        // 调试按钮事件，调用接口
        async handleDebug() {
            const feature = this.form.feature_list[this.featureIdx];
            if (!feature || !feature.modelGroups || !feature.modelGroups.length) {
                this.$message.error("模型组未配置");
                return;
            }

            let success = false;
            let lastError = null;

            console.log('调试启动，本次共', feature.modelGroups.length, '个modelGroup');

            // 遍历 ModelGroup
            for (let groupIdx = 0; groupIdx < feature.modelGroups.length; groupIdx++) {
                const group = feature.modelGroups[groupIdx];
                const models = group.models || [];
                if (!models.length) continue;
                // 当前组prompt/extraPrompt
                let prompt = group.prompt || '';
                let extraPrompt = group.extraPrompt || '';
                let promptPreview = (prompt || '').substr(0, 30).replace(/\n/g, ' ') + '...';

                console.log(`\n--- 尝试第${groupIdx + 1}组 modelGroup, prompt预览:`, prompt);

                // 遍历本组的每一个模型
                for (let modelIdx = 0; modelIdx < models.length; modelIdx++) {
                    const curModel = models[modelIdx];
                    // 组装 prompt
                    let realPrompt = prompt;
                    if (extraPrompt) {
                        realPrompt = realPrompt + '\n' + this.debugParamsContent + '\n' + extraPrompt;
                    } else {
                        realPrompt = realPrompt + '\n' + this.debugParamsContent;
                    }
                    let shortPrompt = realPrompt.substr(0, 40).replace(/\n/g, ' ') + '...';
                    // 控制台打印
                    console.log(`[${new Date().toLocaleTimeString()}] 尝试第${groupIdx + 1}组-第${modelIdx + 1}号模型 ${curModel}`);
                    console.log('prompt内容预览:', realPrompt);

                    // 构造消息体
                    let messages = [{
                        role: "user",
                        content: [
                            { type: "text", text: realPrompt }
                        ]
                    }];

                    // -- 超时处理
                    const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject(new Error("timeout")), 3000));
                    const fetchPromise = fetch("https://api-st.siliconflow.cn/v1/chat/completions", {
                        method: "POST",
                        body: JSON.stringify({
                            model: curModel,
                            messages,
                            stream: true,
                            response_format: { type: "text" },
                            temperature: 0.7,
                            max_tokens: 4000,
                            top_p: 1,
                            frequency_penalty: 0,
                            top_k: 50
                        }),
                        headers: {
                            "Content-Type": "application/json",
                            Authorization: `Bearer sk-tcmxreifxtoyrbjjwcddwlxxqhieysozdluqfnoosmeoeeej`
                        }
                    });

                    this.debugLoading = true;

                    try {
                        let response;
                        try {
                            response = await Promise.race([fetchPromise, timeoutPromise]);
                        } catch (raceError) {
                            if (raceError && raceError.message === "timeout") {
                                // 超时
                                console.warn(`[${new Date().toLocaleTimeString()}] --- [超时] ${curModel}, 进入下一个模型`);
                                continue;
                            }
                            // fetch出错
                            lastError = raceError;
                            console.error(`[${new Date().toLocaleTimeString()}] --- [接口异常] ${curModel}:`, raceError);
                            continue;
                        }
                        // fetch成功
                        if (!response.ok) {
                            lastError = new Error("接口" + curModel + "异常");
                            console.error(`[${new Date().toLocaleTimeString()}] --- [接口状态异常] ${curModel}`);
                            continue;
                        }

                        this.messageRes.content = "";
                        const reader = response.body.getReader();
                        const decoder = new TextDecoder("utf-8");
                        let receivedData = "";
                        const that = this;

                        function processMessages() {
                            const messages = receivedData.split("\n");
                            for (let i = 0; i < messages.length - 1; i++) {
                                that.formatDataStr(messages[i], that.handleResult);
                            }
                            receivedData = messages[messages.length - 1];
                        }

                        async function readStream() {
                            while (true) {
                                const { done, value } = await reader.read();
                                if (done) {
                                    // let content = that.messageRes.content;
                                    // if (!/^```json/.test(content.trim())) {
                                    //     try {
                                    //         content = JSON.stringify(JSON.parse(content), null, 2);
                                    //     } catch { }
                                    //     content = "```json\n" + content + "\n```";
                                    // }
                                    // that.messageRes.content = content;
                                    return;
                                }
                                receivedData += decoder.decode(value);
                                if (receivedData.includes("\n")) processMessages();
                            }
                        }
                        await readStream();

                        this.debugLoading = false;
                        console.log(`[${new Date().toLocaleTimeString()}] --- 成功返回: ${curModel}, 本次调试结束`);
                        success = true;
                        return; // 成功就退出
                    } catch (err) {
                        lastError = err;
                        console.error(`[${new Date().toLocaleTimeString()}] --- [流处理异常] ${curModel}:`, err);
                        // 下一个模型
                    } finally {
                        this.debugLoading = false;
                    }
                }
                // 本组全部失败，自动切下一个组
                console.warn(`[${new Date().toLocaleTimeString()}] >>> 第${groupIdx + 1}组所有模型均失败, 进入下一个group`)
            }
            // 所有分支都失败了
            if (!success) {
                this.$message.error("所有模型接口均未响应，可重试或检查配置。");
                this.messageRes = { content: '调试全部异常: ' + (lastError && (lastError.msg || lastError.message)) };
                console.error('【全部失败】最后的错误:', lastError);
            }
        },
        formatDataStr(str, callback) {
            str.split("\n").forEach((line) => {
                if (line.trim().length > 20) {
                    line.split("data:").forEach((dataSection) => {
                        if (dataSection.trim().length > 10) {
                            const dataObject = JSON.parse(dataSection.trim());
                            if (dataObject.choices[0].delta.content) {
                                callback(dataObject.choices[0].delta.content);
                            }
                        }
                    });
                }
            });
        },
    },
    mounted() { this.fetchList() }
}
</script>


<style scoped>
.tools-btn {
    color: #E6A23C;
}

.import-btn {
    margin-left: 20px;
    /* 标题和按钮之间加距 */
    vertical-align: middle;
}

/* 表单区域样式 */
.form-section {
    margin-bottom: 24px;
}

.form-section:last-child {
    margin-bottom: 0;
}

/* 区域标题 */
.section-title {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 16px;
    padding-bottom: 8px;
    border-bottom: 1px solid #409EFF;
    position: relative;
}

.section-subtitle {
    font-size: 12px;
    font-weight: 400;
    color: #909399;
    margin-left: 8px;
}

/* 功能卡片 */
.feature-list {
    margin-bottom: 16px;
}

.feature-card {
    background: #fafbfc;
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 16px;
    transition: all 0.3s ease;
}

.feature-card:hover {
    border-color: #c6e2ff;
    box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.feature-card:last-child {
    margin-bottom: 0;
}

/* 功能头部 */
.feature-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding-bottom: 8px;
    border-bottom: 1px solid #ebeef5;
}

.feature-index {
    font-size: 14px;
    color: #409EFF;
}

/* 模型组相关 */
.model-groups {
    margin-top: 16px;
}

.model-group-title {
    font-size: 14px;
    font-weight: 500;
    color: #606266;
    margin-bottom: 12px;
}

.model-group-card {
    background: #ffffff;
    border: 1px solid #ebeef5;
    border-radius: 6px;
    padding: 16px;
    margin-bottom: 12px;
    transition: border-color 0.3s ease;
}

.model-group-card:hover {
    border-color: #c6e2ff;
}

.model-group-card:last-child {
    margin-bottom: 0;
}

.model-group-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
}

.model-group-index {
    font-size: 13px;
    color: #909399;
    font-weight: 500;
}

/* 删除按钮 */
.delete-btn {
    color: #f56c6c;
    padding: 0;
}

.delete-btn:hover {
    color: #f56c6c;
    background: transparent;
}

/* 新增按钮区域 */
.add-group-btn {
    text-align: center;
    margin-top: 12px;
    padding-top: 12px;
    border-top: 1px dashed #dcdfe6;
}

.add-feature-btn {
    text-align: center;
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px dashed #dcdfe6;
}

/* 底部按钮 */
.dialog-footer {
    text-align: right;
    padding-top: 16px;
    border-top: 1px solid #ebeef5;
}

/* 响应式调整 */
@media (max-width: 768px) {

    .feature-header,
    .model-group-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 8px;
    }

    .delete-btn {
        align-self: flex-end;
    }
}

/* Element UI 组件样式微调 */
.el-form-item {
    margin-bottom: 18px;
}

.el-form-item:last-child {
    margin-bottom: 0;
}

.el-textarea__inner {
    font-family: inherit;
    line-height: 1.5;
}

.el-select .el-tag {
    margin-right: 4px;
}

/* 滚动条样式 */
.el-dialog__body {
    max-height: 70vh;
    overflow-y: auto;
}

.el-dialog__body::-webkit-scrollbar {
    width: 6px;
}

.el-dialog__body::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
}

.el-dialog__body::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 3px;
}

.el-dialog__body::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
}

::v-deep .vuepress-markdown-body pre,
.vuepress-markdown-body pre[class*="v-md-prism-"] {
    color: none !important;
    padding: 10px;
    margin: 10px;
}

::v-deep .vuepress-markdown-body div[class*="v-md-pre-wrapper-"]:before {
    position: absolute;
    top: 8px;
    right: 10px;
    z-index: 3;
}

::v-deep .vuepress-markdown-body pre[class*="v-md-prism-"] {
    padding: 20px;
}

::v-deep .vuepress-markdown-body code {
    padding: 2px 4px;
    margin: 0 2px;
    color: #fff;
    background: rgba(93, 99, 107, 0.5);
}

::v-deep .vuepress-markdown-body:not(.custom) {
    padding: 20px;
}
</style>